<template>
  <div class="edit-teacher">
    <h1 class="page-title">编辑教师</h1>
    
    <div class="form-container" v-loading="loading">
      <el-form 
        :model="teacherForm" 
        :rules="rules" 
        ref="teacherFormRef" 
        label-width="100px"
        class="teacher-form"
      >
        <el-form-item label="教师工号" prop="teacherId">
          <el-input v-model="teacherForm.teacherId" disabled></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="teacherForm.name" placeholder="请输入教师姓名"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="teacherForm.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="teacherForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="teacherForm.phone" placeholder="请输入电话号码"></el-input>
        </el-form-item>
        <el-form-item label="所属部门" prop="department">
          <el-input v-model="teacherForm.department" placeholder="请输入所属部门"></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="teacherForm.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="goBack">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';

const router = useRouter();
const route = useRoute();
const teacherFormRef = ref(null);
const loading = ref(false);

// 获取教师ID
const teacherId = route.params.id;

// 表单数据
const teacherForm = reactive({
  id: '',
  teacherId: '',
  name: '',
  gender: 1,
  email: '',
  phone: '',
  department: '',
  status: 1
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入教师姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
};

// 获取教师信息
const fetchTeacherInfo = async () => {
  loading.value = true;
  try {
    const response = await axios.get(`/api/admin/teacher/${teacherId}`);
    if (response.data && response.data.success) {
      const teacherData = response.data.data;
      Object.keys(teacherForm).forEach(key => {
        if (key in teacherData) {
          teacherForm[key] = teacherData[key];
        }
      });
    } else {
      ElMessage.error(response.data.message || '获取教师信息失败');
      goBack();
    }
  } catch (error) {
    console.error('获取教师信息错误:', error);
    ElMessage.error('获取教师信息失败，请稍后重试');
    goBack();
  } finally {
    loading.value = false;
  }
};

// 提交表单
const submitForm = async () => {
  if (!teacherFormRef.value) return;
  
  await teacherFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await axios.put(`/api/admin/teacher/${teacherForm.id}`, teacherForm);
        if (response.data && response.data.success) {
          ElMessage.success('更新教师信息成功');
          router.push('/admin/teachers');
        } else {
          ElMessage.error(response.data.message || '更新教师信息失败');
        }
      } catch (error) {
        console.error('提交教师表单错误:', error);
        ElMessage.error(error.response?.data?.message || '操作失败，请稍后重试');
      }
    } else {
      return false;
    }
  });
};

// 重置表单
const resetForm = () => {
  fetchTeacherInfo();
};

// 返回
const goBack = () => {
  router.push('/admin/teachers');
};

// 页面加载时获取教师信息
onMounted(() => {
  if (teacherId) {
    fetchTeacherInfo();
  } else {
    ElMessage.error('缺少教师ID参数');
    goBack();
  }
});
</script>

<style scoped>
.edit-teacher {
  padding: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 24px;
  color: #333;
}

.form-container {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.teacher-form {
  max-width: 600px;
}
</style> 